package wec_wallet.ebo.com.activity.capital;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.HashMap;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.MyBaseActivity;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import wec_wallet.ebo.com.utils.URLs;
import bassproject.ebo.com.ebobass.qrcode.dommy.qrcode.util.Constant;
import bassproject.ebo.com.ebobass.qrcode.google.zxing.activity.CaptureActivity;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.JsonT;
import bassproject.ebo.com.ebobass.utils.PermissionUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.bean.Address;
import wec_wallet.ebo.com.common.Constants;
import wec_wallet.ebo.com.utils.Functions;

public class AccountAddressActivity extends MyBaseActivity {

    @BindView(R.id.account_address_name)
    EditText accountAddressName;
    @BindView(R.id.account_address_address)
    EditText accountAddressAddress;
    @BindView(R.id.account_address_qrcode)
    LinearLayout accountAddressQrcode;
    @BindView(R.id.account_address_submit)
    Button accountAddressSubmit;
    @BindView(R.id.account_address_prompt)
    TextView accountAddressPrompt;
    @BindView(R.id.account_address_delete)
    TextView accountAddressDelete;
    String coinname;
    Address address;
    @BindView(R.id.actionbar_title)
    TextView actionbarTitle;
    @BindView(R.id.activity_setting)
    RelativeLayout activitySetting;
    //打开扫描界面请求码
    private int REQUEST_CODE = 0x01;
    //扫描成功返回码
    private int RESULT_OK = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_address);
        ButterKnife.bind(this);
        initViews();
    }

    @Override
    public void initViews() {
        address = (Address) getIntent().getSerializableExtra("address");
        accountAddressDelete.setVisibility(address == null ? View.GONE : View.VISIBLE);
        actionbarTitle.setText(address == null ? getResources().getString(R.string.account_address) : getResources().getString(R.string.edit_address));
        accountAddressSubmit.setText(address == null ? getResources().getString(R.string.account_address_submit) : getResources().getString(R.string.save));
        coinname = getIntent().getStringExtra(Constants.WALLETID);
        boolean flag = getIntent().getBooleanExtra("flag", false);
        if (flag) {
            String[] primissions = {Manifest.permission.VIBRATE, Manifest.permission.CAMERA};
            PermissionUtils.getInstance().checkPermission(this, primissions, new PermissionUtils.OnPermissionChangedListener() {
                @Override
                public void onGranted() {
                    startCaptureActivity();
                }

                @Override
                public void onDenied() {
                    IToast.show(getResources().getString(bassproject.ebo.com.ebobass.R.string.permission_failed));
                }
            });

        }
        findViewById(R.id.actionbar_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        if (TextUtils.isEmpty(coinname)) {
//            finish();
//        }
        if (null != address) {
            accountAddressName.setText(address.getName());
            accountAddressAddress.setText(address.getAddress());
        }
    }


    @Override
    public void onClick(View v) {

    }

    @OnClick({R.id.account_address_delete, R.id.account_address_submit, R.id.account_address_qrcode})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.account_address_delete:
                deleteAddress();
                break;
            case R.id.account_address_submit:
                if (address == null) {
                    addAddress();
                } else {
                    updateAddress();
                }

                break;
            case R.id.account_address_qrcode:

                String[] primissions = {Manifest.permission.VIBRATE, Manifest.permission.CAMERA};
                PermissionUtils.getInstance().checkPermission(this, primissions, new PermissionUtils.OnPermissionChangedListener() {
                    @Override
                    public void onGranted() {
                        startCaptureActivity();
                    }

                    @Override
                    public void onDenied() {
                        IToast.show(getResources().getString(bassproject.ebo.com.ebobass.R.string.permission_failed));
                    }
                });

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { //RESULT_OK = -1
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            accountAddressAddress.setText(scanResult);
        }
    }

    private void startCaptureActivity() {
        Intent intent = new Intent(AccountAddressActivity.this, CaptureActivity
                .class);
        startActivityForResult(intent, REQUEST_CODE);
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
//                                           @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == Constants.ImgPermissions) {
//            startCaptureActivity();
//        }
//    }

    private void addAddress() {
        if (I_Share.isLogin()) {
            if (TextUtils.isEmpty(accountAddressName.getText().toString().trim())) {
                IToast.show(getResources().getString(R.string.account_address_add));
                return;
            }
            if (TextUtils.isEmpty(accountAddressAddress.getText().toString().trim())) {
                IToast.show(getResources().getString(R.string.account_address_ad_hint));
                return;
            }

            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            postParams.put("coinname", "WEC");
            postParams.put("name", accountAddressName.getText().toString().trim());
            postParams.put("address", accountAddressAddress.getText().toString().trim());
            Functions.post(this, URLs.ADDADDRESS, postParams, new IHttpPostListener() {
                @Override
                public void responseSuccess(String result) {
                    if (Ipost.isTimeOut(result)) {
                        return;
                    }
                    try {
                        if (!TextUtils.isEmpty(result)) {
                            JsonT<String> json = JSON.parseObject(result, new TypeReference<JsonT<String>>() {
                            });
                            if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                                Functions.relogin(AccountAddressActivity.this);
                                return;
                            }
                            if (json.getError() == 0) {
                                IToast.show(getResources().getString(R.string.add_success));
                                finish();
                            } else if (json.getError() == 1) {
                                IToast.show(getResources().getString(R.string.address_data_error));
                            }
                        }
                    } catch (Exception e) {
                        IToast.show(getResources().getString(R.string.data_error));
                    }
                }

                @Override
                public void onTimeOut() {

                }
            }, true, false);
        } else {
            finish();
        }
    }

    private void deleteAddress() {
        if (I_Share.isLogin()) {
            if (TextUtils.isEmpty(address.getId())) {
                IToast.show(getResources().getString(R.string.delete_error));
                return;
            }

            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            postParams.put("addressid", address.getId());
            Functions.post(this, URLs.DELETEADDRESS, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {

                }

                @Override
                public void responseSuccess(String result) {
                    if (Ipost.isTimeOut(result)) {
                        return;
                    }
                    try {


                        if (!TextUtils.isEmpty(result)) {
                            JsonT<String> json = JSON.parseObject(result, new TypeReference<JsonT<String>>() {
                            });
                            if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                                Functions.relogin(AccountAddressActivity.this);
                                return;
                            }
                            if (json.getError() == 0) {
                                IToast.show(getResources().getString(R.string.delete_success));
                                finish();
                            } else if (json.getError() == 1) {
                                IToast.show(json.getError_msg());
                            }
                        }
                    } catch (Exception e) {
                        IToast.show(getResources().getString(R.string.data_error));
                    }
                }
            }, true, false);
        } else {
            finish();
        }
    }

    private void updateAddress() {
        if (I_Share.isLogin()) {
            if (TextUtils.isEmpty(accountAddressName.getText().toString().trim())) {
                IToast.show(getResources().getString(R.string.account_address_add));
                return;
            }
            if (TextUtils.isEmpty(accountAddressAddress.getText().toString().trim())) {
                IToast.show(getResources().getString(R.string.account_address_ad_hint));
                return;
            }
            if (TextUtils.isEmpty(address.getAddress())
                    && accountAddressAddress.getText().toString().trim().equals(address.getAddress())
                    && TextUtils.isEmpty(address.getName())
                    && accountAddressAddress.getText().toString().trim().equals(address.getName())) {
                IToast.show(getResources().getString(R.string.edit_address_null));
                return;
            }
            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            postParams.put("addressid", address.getId());
            postParams.put("name", accountAddressName.getText().toString().trim());
            postParams.put("address", accountAddressAddress.getText().toString().trim());
            Functions.post(this, URLs.UPDATEADDRESS, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {

                }

                @Override
                public void responseSuccess(String result) {
                    if (Ipost.isTimeOut(result)) {
                        return;
                    }
                    try {
                        if (!TextUtils.isEmpty(result)) {
                            JsonT<String> json = JSON.parseObject(result, new TypeReference<JsonT<String>>() {
                            });
                            if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                                Functions.relogin(AccountAddressActivity.this);
                                return;
                            }
                            if (json.getError() == 0) {
                                IToast.show(getResources().getString(R.string.change_success));
                                finish();
                            } else if (json.getError() == 1) {
                                IToast.show(getResources().getString(R.string.address_data_error));
                            }
                        }
                    } catch (Exception e) {
                        IToast.show(getResources().getString(R.string.data_error));
                    }

                }
            }, true, false);
        } else {
            finish();
        }
    }

    @OnClick(R.id.activity_setting)
    public void onViewClicked() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(activitySetting.getWindowToken(), 0); //强制隐藏键盘
    }
}
